package fr.axones.pocketagile.services.remote.util
{
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.IResponder;
	import mx.rpc.events.ResultEvent;
	
	import org.spicefactory.lib.reflect.types.Void;

	public class ResultHandler
	{
		public var token:AsyncToken = new AsyncToken();
		
		private var req:URLRequest;
		private var loader:URLLoader;
		private var status:int;
		
		private var completed:Boolean = false;
		private var statusChanged:Boolean = false;
		
		public function ResultHandler()
		{
		}
		
		public function doGet(url:String):void
		{
			loadURL(URLRequestMethod.GET,url);
		}
		
		public function doPost(url:String, data:String):void
		{
			loadURL(URLRequestMethod.POST,url,data);
		}
		
		public function doPut(url:String, data:String):void
		{
			loadURL(URLRequestMethod.PUT,url,data);
		}
		
		public function doDelete(url:String):void
		{
			loadURL(URLRequestMethod.DELETE,url);
		}
		
		private function loadURL(method:String, url:String, data:String=null):void
		{
			req = new URLRequest(url);
			req.method = method;
			req.data=data;
			
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,completeResponse);
			loader.addEventListener(IOErrorEvent.IO_ERROR,errorResponse);
			loader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS,httpResponse);
			
			loader.load(req);
		}
		
		private function httpResponse(event:HTTPStatusEvent):void 
		{
			statusChanged = true;
			status = event.status;
			successResponse();
		}
		
		private function completeResponse(event:Event):void 
		{
			completed = true;
			successResponse();
		}
		
		private function successResponse():void
		{
			if(completed && statusChanged)
			{
				for each (var responder:IResponder in token.responders) 
				{
					responder.result(new ResultEvent(ResultEvent.RESULT, false, true, {data:loader.data, status:status}));
				}
			}			
		}
		
		private function errorResponse(event:IOErrorEvent):void 
		{
			for each (var responder:IResponder in token.responders) 
			{
				responder.result(new ResultEvent(ResultEvent.RESULT, false, true, loader.data));
			}
		}
	}
}